package b_workqueue;

import com.rabbitmq.client.*;
import org.junit.Test;
import utils.RabbitMQUtils;

import java.io.IOException;

public class Consumer1 {
    @Test
    public void receiveMessage() throws Exception {
        Connection connection = RabbitMQUtils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare("hello", false, false, false, null);

        //设置一次只接收一条未确认的消息
        channel.basicQos(2);
        //接收消息 参数 2:关闭自动确认消息
        channel.basicConsume("hello", false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者【1】收到消息：" + new String(body));
                //手动签收消息
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
        System.out.println("消费者【1】启动成功");
        //不能让程序结束
        System.in.read();
        //关闭
        RabbitMQUtils.closeChannelAndConnection(channel, connection);
    }
}